package jp.co.sharp.android.parents.kidsguard.activity.setting;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.edit.ContactAddActivity;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.adapter.PeriodSettingItemAdaptor;
import jp.co.sharp.android.parents.kidsguard.activity.setting.adapter.PersonalAlarmSettingItemAdaptor;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.dto.ContactListDto;
import jp.co.sharp.android.parents.kidsguard.dto.ContactListsDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

public class PersonalAlarmSettingActivity extends AppCompatActivity {

    private App mApp;
    public ParentBleTransfer mParentBleTransfer;

    private KidInfoEntity mKidInfoEntity;
    private DealWithWaitingDlg mDealWithWaitingDlg;
    private DelDeviceConfirmDlg mDelDeviceConfirmDlg;

    private String macAddress;
    private boolean mEditFlag = false;
    private boolean mLockFlag = false;
    private int mViewProcess = 0;

    private JSONObject mSetSecurityBuzzer = new JSONObject();
    private Button mSubmitBtn;
    private Switch mSwBuzzerState;
    private Switch mSwBuzzerPhoneState;
    private TextView mSwBuzzerStateOnCall;
    private JSONObject mNewJSONObj;
    private ListView mListView;
    private List<ContactListsDto> mContactLists;
    private PersonalAlarmSettingItemAdaptor mAdaptor;

    private boolean mScreenOperate = false;
    private boolean mUnReceiver = true;
    private static final String TAG = "TAG";
    // ページジャンプ
    public static boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;

    private final static int SUCCESS_CODE = 200;
    private final static int PERSONAL_BIZZER_SETTING_REQUEST_CODE = 101;
    private final static int CONTACT_OPT_REQUEST_CODE = 100;
    // プログラムロック
    private String mSyncLock = "syncLock";
    // 編集を再開しています...
    private boolean mEditReopening = false;
    private static final int PAGE_EDIT_REOPEN = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "PersonalAlarmSettingActivity_onCreate");
        setContentView(R.layout.activity_personal_alarm_setting);


        // TODO
        mApp = (App) getApplication();
        initReceiver();
        initData();
        SWChecked();
        mListView = findViewById(R.id.contactList);

        // 検索中...
        String pDlgMsg = "キッズケータイから情報を取得しています....";
        mDealWithWaitingDlg = new DealWithWaitingDlg(PersonalAlarmSettingActivity.this, R.style.dealWithWaitingDlg, pDlgMsg, true);
        mDealWithWaitingDlg.show();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "PersonalAlarmSettingActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if (mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT) {
                    Message msg = new Message();
                    msg.what = PAGE_EDIT_REOPEN;
                    handler.sendMessage(msg);
                }
                mSystemHomeFlag = false;
            }
        }

    }

    @Override
    protected void onStop() {
        Log.i(TAG, "PersonalAlarmSettingActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onStop();

    }

    @Override
    protected void onDestroy() {

        Log.i(TAG, "PersonalAlarmSettingActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onDestroy();
    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        Log.i(TAG,"PersonalAlarmSettingActivity_onBackPressed");
        backActivity(null);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "PersonalAlarmSettingActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "PersonalAlarmSettingActivity_onActivityResult");
        initReceiver();
        if (resultCode == SUCCESS_CODE) {
            if (requestCode == PERSONAL_BIZZER_SETTING_REQUEST_CODE) {
                String buzzer = data.getStringExtra("buzzer");
                TextView textView = findViewById(R.id.buzzerStateOnCall);
                textView.setText(buzzer);
                try {
                    mSetSecurityBuzzer.getJSONObject("data").put("buzzerStateOnCall", buzzer.equals("消音する") ? 0 : 1);
                    controlSubmitBtnChange();
                } catch (JSONException e) {
                    Log.e(TAG, e.getMessage());
//                    e.printStackTrace();
                }
            }
        }else if (resultCode == CONTACT_OPT_REQUEST_CODE) {
            if(requestCode == 100){
                ContactListDto contactListDto = (ContactListDto) data.getSerializableExtra(Constants.KEY_CONTACT_OPT);
                int position = data.getIntExtra("position", -1);
                mContactLists.get(position).setName(contactListDto.getName());
                mContactLists.get(position).setId(contactListDto.getId());
                mContactLists.get(position).setPhone(contactListDto.getPhone());
                mAdaptor.notifyDataSetChanged();

                try {
                    List<ContactListsDto> contactList = new ArrayList<>();
                    for (ContactListsDto dto:mContactLists) {
                        if(null!=dto.getId()){
                            contactList.add(dto);
                        }
                    }
                    JSONArray array = new JSONArray(contactList.toString());
                    mSetSecurityBuzzer.getJSONObject("data").put("phoneList", array);
                    controlSubmitBtnChange();
                } catch (JSONException e) {
                    Log.e(TAG, e.getMessage());
//                e.printStackTrace();
                }
            }
        }
    }

    public void backActivity(View view) {
        Log.i(TAG, "PersonalAlarmSettingActivity_backActivity");
        try {
            if (!mSetSecurityBuzzer.getJSONObject("data").toString().equals(mNewJSONObj.getJSONObject("data").toString())) {
                String message = "編集内容は保存されていません。編集内容を破棄して前の画面に戻りますか？";
                mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(PersonalAlarmSettingActivity.this, R.style.commonDlg, message);
                mDelDeviceConfirmDlg.show();
                mDelDeviceConfirmDlg.setOnOperateSetListener(new DelDeviceConfirmDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT, PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING, mParentBleTransfer, mKidInfoEntity).start();
                        mPageJumpFlag=true;
                        PersonalAlarmSettingActivity.this.finish();
                    }
                });
            } else {
                new BusinessThread(Constants.SEND_KID_EXIT, PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING, mParentBleTransfer, mKidInfoEntity).start();
                mPageJumpFlag=true;
                PersonalAlarmSettingActivity.this.finish();
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }


    /**
     * Receiver
     */
    public void initReceiver() {
        Log.i(TAG, "PersonalAlarmSettingActivity_initReceiver");


        mKidInfoEntity = ((App) getApplication()).findKidInfoBySelect();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // Bluetooth
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
//        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);

        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }

    /**
     * Activity
     */
    public void initData() {
        Log.i(TAG, "PersonalAlarmSettingActivity_initData");
        TextView alarmSetting = findViewById(R.id.alarmSetting);
        alarmSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(PersonalAlarmSettingActivity.this, PersonalBizzerSettingActivity.class);
                TextView textView = findViewById(R.id.buzzerStateOnCall);
                i.putExtra("buzzerAlarm", textView.getText());
                startActivityForResult(i, PERSONAL_BIZZER_SETTING_REQUEST_CODE);
            }
        });

        mSubmitBtn = findViewById(R.id.submit);
        mSwBuzzerState = findViewById(R.id.buzzerState);
        mSwBuzzerPhoneState = findViewById(R.id.buzzerPhoneState);
        mSwBuzzerStateOnCall = findViewById(R.id.buzzerStateOnCall);

        mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));

        mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String message = "キッズケータイへ反映中..";
                mDealWithWaitingDlg = new DealWithWaitingDlg(PersonalAlarmSettingActivity.this, R.style.commonDlg, message, true);
                mDealWithWaitingDlg.show();
                new BusinessThread(Constants.SEND_KID_SET_INFO, mParentBleTransfer, mKidInfoEntity, submitData(), PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING).start();
            }
        });

        macAddress = ((App) getApplication()).findKidInfoBySelect().getMacAddress();
        new BusinessThread(Constants.SEND_KID_IS_USING, mParentBleTransfer, mKidInfoEntity).start();
    }


    /**
     * getRequest
     */
    private JSONObject getInitData() {
        Log.i(TAG, "PersonalAlarmSettingActivity_getInitData");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("method", RequestMethodConstants.METHOD_GET_SECURITY_BUZZER);
            jsonObject.put("data", JSONObject.NULL);
//            mParentBleTransfer.writeLeData(mApp.findKidInfoBySelect().getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
//            e.printStackTrace();
        }
        return jsonObject;
    }

    /*
     * submit
     */
    private JSONObject submitData() {
        Log.i(TAG, "PersonalAlarmSettingActivity_submitData");
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("method", RequestMethodConstants.METHOD_SET_SECURITY_BUZZER);
            jsonObject.put("data", mSetSecurityBuzzer.getJSONObject("data"));
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
//            e.printStackTrace();
        }
        return jsonObject;
    }


    public void controlSubmitBtnChange() throws JSONException {
        Log.i(TAG, "PersonalAlarmSettingActivity_controlSubmitBtnChange");
        if (mSetSecurityBuzzer.getJSONObject("data").toString().equals(mNewJSONObj.getJSONObject("data").toString())) {
            mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
            mSubmitBtn.setClickable(false);
        } else {
            mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
            mSubmitBtn.setClickable(true);
        }

    }

    public void SWChecked() {
        mSwBuzzerPhoneState.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.i(TAG, "PersonalAlarmSettingActivity_onCheckedChanged");
                try {
                    int data = isChecked ? 0 : 1;
                    mSetSecurityBuzzer.getJSONObject("data").put("buzzerPhoneState", data);
                    controlSubmitBtnChange();
                } catch (JSONException e) {
                    Log.e(TAG, e.getMessage());
//                    e.printStackTrace();
                }
            }
        });

        mSwBuzzerState.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.i(TAG, "PersonalAlarmSettingActivity_setOnCheckedChangeListener");
                try {
                    int data = isChecked ? 0 : 1;
                    mSetSecurityBuzzer.getJSONObject("data").put("buzzerState", data);
                    controlSubmitBtnChange();
                } catch (JSONException e) {
                    Log.e(TAG, e.getMessage());
//                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_INIT);
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT, PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING, mParentBleTransfer, mKidInfoEntity).start();
                    }

                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            Message msg = new Message();
                            msg.what = PAGE_EDIT_REOPEN;
                            handler.sendMessage(msg);
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mSystemHomeFlag = true;
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT, mParentBleTransfer, mKidInfoEntity, null, PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING).start();
                    }
                }else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (mApp.isMimamoriCheck(macAddress)) {
                        mApp.addmLsIsMimamori(macAddress);
                        // TODO Mimamori
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING).start();

                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(PersonalAlarmSettingActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        mApp.updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(PersonalAlarmSettingActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                // ページジャンプ
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(PersonalAlarmSettingActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };
    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "PersonalAlarmSettingActivity_BroadcastReceiver");
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (bluetoothReceiverDto.isFinished()) {
                        switch (mViewProcess) {
                            case Constants.SEND_KID_ENTER:
                                mEditFlag = true;
                                mViewProcess = Constants.SEND_KID_GET_INFO;
                                if (!mScreenOperate) {
                                    new BusinessThread(Constants.SEND_KID_GET_INFO, mParentBleTransfer, mKidInfoEntity, getInitData(), PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING).start();
                                } else {
                                    mEditReopening = false;
                                    mScreenOperate = false;
                                    handler.sendEmptyMessage(0);
                                }
                                break;
                            case Constants.SEND_KID_EXIT:
                                mEditFlag = false;
                                if (null != mDelDeviceConfirmDlg && mDelDeviceConfirmDlg.isShowing()) {
                                    mDelDeviceConfirmDlg.dismiss();
                                }
                                if (!mScreenOperate) {
                                    // ページジャンプ
                                    mPageJumpFlag = true;
                                    PersonalAlarmSettingActivity.this.finish();
                                }
                                break;
                        }
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String retStr = bluetoothReceiverDto.getRetStr();
                    JSONObject mJsonObject = new JSONObject(retStr);

                    if (mLockFlag && RequestMethodConstants.METHOD_GET_SECURITY_BUZZER.equals(mJsonObject.getString("method"))) {
                        mSetSecurityBuzzer = new JSONObject(mJsonObject.toString());
                        mNewJSONObj = mJsonObject;
                        mDealWithWaitingDlg.dismiss();
                        //getUser
                        TextView tv_user = findViewById(R.id.user);
                        tv_user.setText(mApp.findKidInfoBySelect().getKidName() + "のキッズケータイ");

                        //switch init
                        switchInit(mJsonObject);

                        //buzzerPhoneState init
                        buzzerPhoneStateInit(mJsonObject);

                        //buzzerStateOnCall init
                        buzzerStateOnCallInit(mJsonObject);

                        //contactList init
                        contactListInit(mJsonObject);
                        //setAdaptor
                        setAdaptor();


                    } else if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(mJsonObject.getString("method"))) {
                        JSONObject data = mJsonObject.getJSONObject("data");
                        if (Constants.IS_USING_OK.equals(data.getString("state"))) {
                            //send enter
                            mLockFlag = true;
                            mViewProcess = Constants.SEND_KID_ENTER;
                            new BusinessThread(Constants.SEND_KID_ENTER, 5, mParentBleTransfer, mKidInfoEntity).start();
                        } else {
                            mDealWithWaitingDlg.dismiss();
                            String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(PersonalAlarmSettingActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                    PersonalAlarmSettingActivity.this.finish();
                                }
                            });
                        }
                    } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(mJsonObject.getString("method"))) {
                        mDealWithWaitingDlg.dismiss();
                        if (Constants.ON_SYNC_RESULT.equals(mJsonObject.getString("result"))) {
                            // ページジャンプ
                            mPageJumpFlag = true;
                            Intent intent1 = new Intent();
                            intent1.setClass(PersonalAlarmSettingActivity.this, SettingActivity.class);
                            startActivity(intent1);
                            //send exit
                            new BusinessThread(Constants.SEND_KID_EXIT, PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING, mParentBleTransfer, mKidInfoEntity).start();
                        }
                    } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(mJsonObject.getString("method"))) {
                        String message = "キッズケータイが操作されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(PersonalAlarmSettingActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {

                                mPageJumpFlag = true;
                                Intent intent1 = new Intent(PersonalAlarmSettingActivity.this,SettingActivity.class);
                                startActivity(intent1);
                                processWarringDlg.dismiss();
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
//                e.printStackTrace();
            }
        }
    };


    public void switchInit(JSONObject jsonObject) throws Exception {
        Log.i(TAG, "PersonalAlarmSettingActivity_switchInit");
        int buzzerState = jsonObject.getJSONObject("data").getInt("buzzerState");
        if (buzzerState == 1) {
            mSwBuzzerState.setChecked(false);
        } else {
            mSwBuzzerState.setChecked(true);
        }
    }

    public void buzzerPhoneStateInit(JSONObject jsonObject) throws Exception {
        Log.i(TAG, "PersonalAlarmSettingActivity_buzzerPhoneStateInit");
        int buzzerPhoneState = jsonObject.getJSONObject("data").getInt("buzzerPhoneState");
        if (buzzerPhoneState == 1) {
            mSwBuzzerPhoneState.setChecked(false);
        } else {
            mSwBuzzerPhoneState.setChecked(true);
        }
        ;
    }

    public void buzzerStateOnCallInit(JSONObject jsonObject) throws Exception {
        Log.i(TAG, "PersonalAlarmSettingActivity_buzzerStateOnCallInit");
        int buzzerStateOnCall = jsonObject.getJSONObject("data").getInt("buzzerStateOnCall");
        if (buzzerStateOnCall == 0) {
            mSwBuzzerStateOnCall.setText("消音する");
        } else {
            mSwBuzzerStateOnCall.setText("消音しない");
        }

    }

    public void contactListInit(JSONObject jsonObject) throws Exception {
        Log.i(TAG, "PersonalAlarmSettingActivity_contactListInit");
        List<ContactListsDto> contactLists = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            ContactListsDto dto = new ContactListsDto();
            dto.setIndex(i);
            dto.setName("おとうさん");
            contactLists.add(dto);
        }

        JSONArray contactJson = jsonObject.getJSONObject("data").getJSONArray("phoneList");
        for (int i = 0; i < contactJson.length(); i++) {
            JSONObject data = (JSONObject) contactJson.get(i);
            int index = data.getInt("index");
            contactLists.get(index).setId(data.getInt("id"));
            contactLists.get(index).setName(data.getString("name"));
            contactLists.get(index).setPhone(data.getString("phone"));
        }

        mContactLists = contactLists;
        mAdaptor = new PersonalAlarmSettingItemAdaptor(PersonalAlarmSettingActivity.this, R.layout.activity_personal_alarm_setting_item, contactLists,
                new PersonalAlarmSettingItemAdaptor.OnClickItemListenter() {
                    @Override
                    public void chooseItemClick(int position) {

                    }
                });
        mListView.setAdapter(mAdaptor);
    }

    public void setAdaptor() {
//        Log.i(TAG, "PersonalAlarmSettingActivity_setAdaptor");
//        mAdaptor = new PersonalAlarmSettingItemAdaptor(PersonalAlarmSettingActivity.this, R.layout.activity_personal_alarm_setting_item, mContactLists,
//                new PersonalAlarmSettingItemAdaptor.OnClickItemListenter() {
//                    @Override
//                    public void chooseItemClick(int position) {
//
//                    }
//                });
//        mListView.setAdapter(mAdaptor);
    }

    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            } else if (msg.what == PAGE_EDIT_REOPEN) {
                if (!mEditReopening) {
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(PersonalAlarmSettingActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    mScreenOperate = true;
                    mViewProcess = Constants.SEND_KID_IS_USING;
                    new BusinessThread(Constants.SEND_KID_IS_USING,
                            mParentBleTransfer,
                            mKidInfoEntity,
                            null,
                            PageSerialNumConstants.PAGE_SERIAL_NUM_POWER_SETTING).start();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                    mEditReopening = true;
                }
            }
        }
    };

}
